package com.yunfei.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源3
 */
@Configuration
@MapperScan(basePackages = "com.yunfei.mapper.aiiidb", sqlSessionTemplateRef  = "aiiidbSqlSessionTemplate")
public class DataSource3Config {
    /**
     * 获取数据源2的配置文件信息
     * @return
     */
    @Bean(name = "aiiidbDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.aiiidb")
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }
    /**
     * 数据源的xml文件路径
     * @return
     */
    @Bean(name = "aiiidbSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("aiiidbDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/aiiidb/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "aiiidbTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("aiiidbDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "aiiidbSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("aiiidbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
